// 云函数入口文件
const cloud = require('wx-server-sdk')
const COS = require('cos-nodejs-sdk-v5');
const xlsx = require('node-xlsx');
const moment = require('moment');
const got = require('got');
const Bucket = 'p-1301301505';
const REGION = 'ap-chongqing';
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;
const $ = _.aggregate;

removeCosFolder = async (bucket, folder) => {
  if (!folder) {
    return false;
  }
  if (!folder.endsWith("/")) {
    folder = folder + "/";
  }

  let cosOptions = {
    Bucket: bucket,
    /* 必须 */
    Region: REGION,
    /* 必须 */
    Prefix: folder,
    /* 非必须 */
    Delimiter: '/',
    /* 非必须 */
  }
  // if (event.Marker){
  //   cosOptions.Marker = event.Marker;
  // }

  return new Promise((resolve, reject) => {
    const cos = new COS({
      SecretId: 'AKIDlJa3GZNOedS0HJJYlUxrVtjJfkhOM0uN',
      SecretKey: 'Xp0bLq4JK4h5DEBsTpwtc6SaRImAHL9i'
    });

    // 获取图片目录，全部删除
    cos.getBucket(cosOptions, function (err, data) {
      // console.log(err||data);
      if (err) {
        if (err.statusCode === 404) {
          resolve(`COS 目录 ${folder} 已不存在`);
        } else {
          resolve(err);
        }
      } else if (data) {
        if (data.Contents.length === 0) {
          resolve(`COS 目录 ${folder} 已全部删除`);
        } else {
          let cosFiles = [];
          data.Contents.map(f => {
            cosFiles.push({
              Key: f.Key
            });
          });
          console.log("即将删除COS文件", cosFiles.length);
          cos.deleteMultipleObject({
            Bucket: BUCKET,
            /* 必须 */
            Region: REGION,
            /* 必须 */
            Quiet: true,
            Objects: cosFiles
          }, function (err1, data1) {
            // console.log(err1||data1);
            if (!err1 && data.IsTruncated === "true") {
              cloud.callFunction({
                name: 'removeCOSFolder',
                data: {
                  folder: folder,
                  Marker: data.Marker
                }
              }).then(res => {
                resolve(res);
              });
            } else {
              resolve(err1 | data1);
            }
          })
        }
      }
    });
  })
}

removeOrder = async (id) => {
  await db.collection('agenda').doc(id).remove();
  // TODO 删除COS图片
  await removeCosFolder(Bucket, `/orders/${id}/`);
  await db.collection('picture').where({
    orderid: id,
  }).remove();
  return await db.collection('order').doc(id).remove();
}

listOrder = async (studioid) => {
  return db.collection('order').aggregate().match({
    studioid: studioid
  }).group({
    _id: '$status',
    num: $.sum(1)
  }).sort({_id: 1}).end();
}

addImage = async (event) => {
  var stat;
  // try{
    stat = await db.collection('picture').doc(event.id).update({
      data: {
       // files: _.push({each: event.nodes, sort: {[event.randomSort?'name':'time']:1}})
       files:event.nodes
      }
    });
    console.log(stat);
    if (stat.stats.updated == 0){
      stat = await db.collection('picture').add({
        data: {
          _id: event.id,
          studioid: event.studioid,
          files: event.nodes,
          randomSort: false,
          createtime: db.serverDate()
        }
      });
    }
  return stat;
}

removeImage = async (event) => {
  return await db.collection('picture').doc(event.id).update({
    data: {
      files: _.pull({
        name: event.name
      })
    }
  });
}

exportFiles = async(event)=>{
  let picture = (await db.collection('picture').doc(event._id).field({files: true}).get()).data;
  if (!picture || !picture.files) return{
    errMsg: '参数错误'
  }
  //1,定义excel表格名
  // let dataCVS = 'test.xlsx'
  //2，定义存储数据的
  let alldata = [];
  let row = ['图片编号','图片名','原片','精修','备注'];
  alldata.push([event.title]);
  alldata.push(row);

  picture.files.sort((a,b)=>{
    return a.time&&b.time?(a.time>b.time?1:-1):(a.name>b.name?1:-1);
  });

  picture.files.map((v,i)=>{
    if (!v.selected && !v.digest) return;
    let arr = [];
    arr.push(i + 1);
    arr.push(v.name);
    arr.push(v.selected||v.digest?'是':'');
    arr.push(v.digest?'是':'');
    arr.push(v.remark);
    alldata.push(arr)
  })
  //3，把数据保存到excel里
  var buffer = await xlsx.build([{
    name: "Sheet1",
    data: alldata
  }]);
  //4，把excel文件保存到云存储里
  return await cloud.uploadFile({
    cloudPath: `choosedXlsx/${moment().format("YYYY-MM")}/${event.title}.xlsx`,
    fileContent: buffer, //excel二进制文件
  })
}

addOrder = async(event) =>{
  console.log("addOrder", event);
  // TODO 向工作室发送消息
  let order = (await db.collection('order').doc(event._id).field({customer: true, studioid: true, price: true, remark: true}).get()).data;
  if (!order){
    return {
      code: 0,
      errmsg: '获取订单失败'
    }
  }
  let users = (await db.collection('team').where({studioid: order.studioid, status:1, job: '管理员'}).field({_openid: true,}).get()).data;
  if (users.length == 0){
    console.log('发送消息失败，工作室没有管理员');
    return {
      code: 0,
      errmsg: '工作室没有管理员'
    }
  }
  let promises = [];
  users.map(v=>{
    let data = {
      // 联系人
      name3: {value: order.customer.name},
      // 联系人电话
      phone_number4: {value: order.customer.phone},
      // 订单金额
      amount5: {value: order.price+'元'},
      // 备注
      thing10: {value: order.remark || '您有新的订单，请确认。'}
    };
    console.log('msg', data);
    let ret = cloud.openapi.subscribeMessage.send({
      touser: v._openid,
      templateId: 'fgN7PR9idyvoDi2-l0JW-ObwnAY5cRIfz1oA002FipU',
      miniprogram_state: 'trial',
      page: `/pages/admin/order/detail/detail?_id=${order._id}`,
      data: data
    });
    promises.push(ret);
  })
  
  try {
     let result = await Promise.all(promises);
     console.log(result);
  } catch (error) {
    console.log(error)
  }
  return event;
}

changeStatus = async(event)=>{
  let data = {
    status: event.status
  };
  if (event.log){
    data.logs = _.push(event.log);
  }
  let res = await db.collection('order').doc(event._id).update({data: data});
  console.log("Update Status", event, res);

  if (event.status == 3){
    await db.collection('agenda').doc(event._id).update({data: {status: 1}});
  }
  // 向用户发送订阅消息
  let msg = null;
  switch(event.status){
    case 2: // 排期通知
      let order = (await db.collection('order').doc(event._id).field({'customer.openid': true, agenda: true}).get()).data;
      console.log(order);
      msg = {
        touser: order.customer.openid,
        templateId: 'pKxDj_0m_42i2_0d2R1K0pWQwV1iukPZVAOx3pLFOFs',
        miniprogram_state: 'trial',
        page: `/pages/user/order/detail/detail?_id=${order._id}`,
        data: {
          date2: {value: order.agenda.date + ' ' + order.agenda.time},
          thing3: {value: order.agenda.location},
          thing6: {value: order.agenda.service},
          thing4: {value: order.agenda.remark || '请注意拍摄时间'}
        }};
      break;
    // case 2: // 排期通知
    //   msg = {};
    //   break;
    case 4: // 选片通知
      // let order = (await db.collection('order').doc(event._id).field({
      //   'customer.openid': true, agenda: true, 'service.title': true
      // }).get()).data;
      // console.log(order);
      // msg = {
      //   touser: order.openid,
      //   templateId: 'f6DYdmUG0hLG_WMB2HI7YfTVBpivm2qDA6naWa59IK8',
      //   miniprogram_state: 'trial',
      //   page: `pages/user/order/detail/detail?_id=${order._id}`,
      //   data: {
      //     date2: {value: order.agenda.date + ' ' + order.agenda.time},
      //     thing3: {value: order.agenda.location},
      //     thing6: {value: order.agenda.service},
      //     thing4: {value: order.agenda.remark || '请您注意时间'}
      //   }};
      break;
    // case 
    default:
      msg = null;
  }

  if (msg){
    let msgResult = await sendMessage();
    console.log('Send message')
    return msgResult;
  }
  return {result: 0};
}

sendMessage = async(msg)=>{
  const appid = "wx53f453674085a5ce";
  const secret = "346b6f46c964a24b6498e6784aff0d04";
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
  let token = (await got(url, {responseType: 'json'})).body;

  // TODO 发消息
  const callUrl = `https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${token.access_token}&env=easyphoto-user-7gb3o971d6433059&name=sendMsg`;
  let res = (await got(callUrl, {
    body: msg,
    form: false,
    json: true})).body;
  return res;
}

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.op) {
    case 'remove':
      return await removeOrder(event._id);
    case 'changeStatus':
      return await changeStatus(event);
    case 'addOrder': // 客户端下单
      return await addOrder(event);
    case 'list':
      return await listOrder(event.studioid);
    case 'addImage':
      return await addImage(event);
    case 'removeImage':
      return await removeImage(event);
    case 'export':
      return await exportFiles(event);
  }
}